using UnityEngine;
using UnityEngine.UI;

namespace FutureCorePlugin
{
    public class UGUIAdaptive : MonoBehaviour
    {
        private CanvasScaler canvasScaler;

        private void Awake()
        {
            canvasScaler = GetComponent<CanvasScaler>();
            Init();
            Adaptive();
        }

#if UNITY_EDITOR
        private float currScreenHeight;
        private float currScreenWidth;

        private void Update()
        {
            if (currScreenHeight != Screen.height || currScreenWidth != Screen.width)
            {
                currScreenHeight = Screen.height;
                currScreenWidth = Screen.width;
                AdaptiveConst.CurrAspectRatio = (float)Screen.height / Screen.width;
                Adaptive();
            }
        }
#endif

        private void Init()
        {
            if (canvasScaler == null) return;

            canvasScaler.referenceResolution = AdaptiveConst.StandardResolution;
            canvasScaler.referencePixelsPerUnit = AdaptiveConst.PixelsPerUnit;
        }

        private void Adaptive()
        {
            if (canvasScaler == null) return;

            if (AdaptiveConst.CurrAspectRatio > AdaptiveConst.StandardAspectRatio)
            {
                canvasScaler.matchWidthOrHeight = AdaptiveConst.MatchWidth;
            }
            else
            {
                canvasScaler.matchWidthOrHeight = AdaptiveConst.MatchHeight;
            }

            gameObject.SetActive(false);
            gameObject.SetActive(true);
        }
    }
}